<template>
    <el-tree ref="treeRef" style="max-width: 600px" :data="data" show-checkbox node-key="id" :default-expand-all="true"
        :default-expanded-keys="expandedKeys" :default-checked-keys="checkedKeys" :props="defaultProps">
        <template #default="{ node, data }">
            <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span style="margin-left: 18px">
                    <el-tag style="margin-right: 18px" type="warning" v-show="data.type == 0">菜单</el-tag>
                    <el-tag style="margin-right: 18px" type="danger" v-show="data.type == 2">接口</el-tag>
                    <el-tag style="margin-right: 18px" type="success" v-show="data.type == 1">按钮</el-tag>

                </span>
            </span>
        </template>
    </el-tree>
    <el-button type="primary" @click="onSubmit">保存</el-button>
    <el-button @click="close">关闭</el-button>
</template>

<script setup>
import { ref, defineEmits, defineProps, onMounted } from 'vue'
import { PowerList as getList, RoleAdd as adds, RolePower } from '../../api/api';
import { ElMessage } from 'element-plus'
const emit = defineEmits(['item']);
const defaultProps = {
    children: 'child',
    label: 'power_name',
}
const data = ref([])
const treeRef = ref();
const expandedKeys = ref([]);
const checkedKeys = ref([]);

onMounted(() => {
    loadList();
    if (props.id) {
        GetRolePower(props.id);
    }
});
const props = defineProps({
    id: {
        type: Number,
        default: NaN
    }
})


const onSubmit = () => {
    let powerData = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys(true)];
    adds({ power_ids: powerData, id: props.id }).then((res) => {
        console.log('res', res)
        ElMessage({
            message: res.msg,
            type: 'success',
        })
        close()
    })
    console.log(powerData)

}
const GetRolePower = (id) => {
    RolePower({ id: id }).then((res) => {
        console.log('res', res.data.checkedKeys)
        expandedKeys.value = res.data.expandedKeys;
        checkedKeys.value = Object.values(res.data.checkedKeys);
        // expandedKeys.value = [1,2];
        // checkedKeys.value =  [3,5];  
        console.log('expandedKeys', expandedKeys.value)
        console.log('checkedKeys', checkedKeys.value)

    })
}
const loadList = () => {
    try {
        // 这里应该是发送登录请求的代码，例如使用axios或者其他HTTP客户端
        getList({}).then((res) => {
            console.log('res', res)
            data.value = res.data

        })

    } catch (error) {
        // 处理登录失败的情况
        console.error('error', error);
        // 可以在这里提示用户登录失败的信息
    }
};
const close = () => {
    emit('item', 'false')
}
</script>